package com.ruoyi.framework.shiro.util.secret;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;

public class Mkey {

    //key seed
    public final String B_KEY = "0bcf0e84c1734443af2169357a2f17f5";
    public final String seed_a = "0bcf0e84c1734443af2169357a2f17f5";
    private String seed_b = "123456";
    private String MKey = "";

    public Mkey() {
        //default init
        init();
    }

    /**
     * init by seed_b.txt
     */
    private void init() {
        try {
            if (MKey.isEmpty()) {
                //统一写死，不读取配置文件，方便维护
                MKey = getSha256(seed_a + seed_b);

            }
        } catch (Exception e) {
        }
    }

    /**
     * init by string
     */
    public void init(String i_seed_b) {
        try {
            if (!i_seed_b.isEmpty()) {
                //get seed b
                seed_b = decryptAesDefault(B_KEY, i_seed_b);
                MKey = getSha256(seed_a + seed_b);
            }
        } catch (Exception e) {
        }

    }


    public byte[] getMkeyKey() throws Exception {
        if (MKey == null || MKey.isEmpty()) {
            return new byte[0];
        }
        byte[] keyBytes = new byte[16]; // 后16byte为key
        byte[] b = Algorithm.decode(MKey, Encoder.Base64);
        System.arraycopy(b, 16, keyBytes, 0, 16);
        return keyBytes;
    }

    public byte[] getMkeyIv() throws Exception {
        if (MKey == null || MKey.isEmpty()) {
            return new byte[0];
        }
        byte[] ivBytes = new byte[16]; // 前16byte为iv
        byte[] b = Algorithm.decode(MKey, Encoder.Base64);
        System.arraycopy(b, 0, ivBytes, 0, 16);
        return ivBytes;
    }

    private String getSha256(String text) {
        try {
            byte[] macBytes = Algorithm.sha256(text);
            String MAC = Algorithm.encode(macBytes, Encoder.Base64);    //bytesToHexString(macBytes)
            return MAC;
        } catch (Exception ex) {
            return null;
        }
    }

    private String getSeedB(String filepath) {
        if (filepath == null || filepath.isEmpty()) {
            return null;
        }
        try (InputStream in = new BufferedInputStream(new FileInputStream(filepath))){
            StringBuilder sb = new StringBuilder();
            byte[] b = new byte[132];

            while (in.read(b) > 0) {
                sb.append(new String(b, StandardCharsets.UTF_8));
            }
            in.close();

            return sb.toString().trim();
        } catch (IOException e) {
            return null;
        }
    }

    private String decryptAesDefault(String secret, String ciphertext) {
        if (secret == null || secret.length() != 32) {
            return null;
        }
        byte[] keyBytes =
                secret.substring(16, 32).getBytes(StandardCharsets.UTF_8); // 后16byte为key
        byte[] ivBytes =
                secret.substring(0, 16).getBytes(StandardCharsets.UTF_8); // 前16byte为iv

        // --- Decrypt ---
        String plaintext = null;
        try {
            byte[] textBytes = Algorithm.decode(ciphertext, Encoder.Base64);
            plaintext = Algorithm.aesDecrypt(textBytes, keyBytes, ivBytes);
        } catch (Exception ex) {
            return null;
        }
        return plaintext;
    }
}
